package com.zhongwang.business.module.quoteManage.quoteManageService;

import com.zhongwang.business.common.JsonResult;
import com.zhongwang.business.gen.entity.*;
import com.zhongwang.business.gen.mapper.*;
import com.zhongwang.business.module.basic.model.ConsumerInfoMainModel;
import com.zhongwang.business.module.basic.model.VerifyProcessModel;
import com.zhongwang.business.module.quoteManage.quoteManageModel.QuotationMainModel;
import com.zhongwang.business.module.quoteManage.quoteManageModel.QuotationPaymentModel;
import com.zhongwang.business.module.quoteManage.quoteManageModel.QuotationSublistModel;
import com.zhongwang.business.module.quoteManage.quoteManageModel.FileManageModel;
import com.zhongwang.business.gen.entity.QuotationPayment;
import com.zhongwang.business.util.FileUtils;
import com.zhongwang.business.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.zhongwang.business.module.quoteManage.quoteManageDao.QuotationMainDao;
import com.zhongwang.business.module.quoteManage.quoteManageDao.QuotationQueryDao;
import com.zhongwang.business.module.system.log.LogService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *  报价任务管理 服务层
 * @author zcy
 * @date 2020/08/20
 */
@Log4j2
@Service
public class QuoteTaskService {
    @Autowired
    private QuotationMainDao quotationMainDao;
    @Autowired
    private QuotationQueryDao quotationQueryDao;
    @Autowired
    private QuotationMainMapper quotationMainMapper;
    @Autowired
    private FileManageMapper fileManageMapper;
    @Autowired
    private QuotationSublistMapper quotationSublistMapper;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private SheetDetailMapper sheetDetailMapper;
    @Autowired
    private VerifyProcessMapper verifyProcessMapper;
    @Autowired
    private QuotationPaymentMapper quotationPaymentMapper;
    @Autowired
    private QttSubTaskRelMapper qttSubTaskRelMapper;
    @Autowired
    private SellerInfoMapper sellerInfoMapper;
    @Autowired
    public LogService logService;
    @Autowired
    public SysUserMapper sysUserMapper;
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
//     * 查询报价任务列表
//     *
//     * @param query 查询条件
//     * @return 报价任务
//     */
//    public List<QuotationMainModel> findQuoteTaskList(query) {
//        return quotationMainDao.selectQuoteTaskList(query);
//    }

    /**
     * 保存从待报价列表任务内选择待报价的明细
     * @param quotationSublistModel 查询项
     * @return
     */
//    public QuotationSublistModel addQuotationList(QuotationSublistModel quotationSublistModel) {
//        quotationSublistModel = quotationMainDao.selectQuotationList(quotationSublistModel.getQuoteTaskId()); //根据id查找报价任务信息
//            TaskFormRelation taskFormRelation = quotationMainDao.selectQttTaskRel(taskModel.getId()); //根据报价id查找关系表的信息
//            QuotationSublist quotationSublist = new QuotationSublist();
//            quotationSublist.setQuoteId(quotationSublistModel.getQuoteId());
//            quotationSublist.setProName(taskModel.getName());
//            quotationSublist.setProQty(taskModel.getNum());
//            quotationSublist.setProUnit(taskModel.getUnit());
//            quotationSublist.setTaskRelationFkId(taskFormRelation.getId());
//            quotationSublist.setQttAvaStatus(1);
//            quotationSublistMapper.insertSelective(quotationSublist);//插入报价明细
//            taskFormRelation.setFkid(quotationSublistModel.getQuoteId());
//            taskFormRelationMapper.updateByPrimaryKeySelective(taskFormRelation);//更新关系表中报价任务对应的id
//            taskModel.setBeginDate(new Date());
//            taskModel.setTstatus(2);
//            quotationMainDao.updateQttTaskStatus(taskModel);
//        return quotationSublistModel;
//    }

    /**
     * 创建报价单主单和明细
     *
     * @param quotationMainModel 报价单主单信息；报价单明细字符串
     * @return 行数
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult quotationCreateSave(QuotationMainModel quotationMainModel, String[] proName, String[] proNames, String[] proType, Double[] proQty,
                                                String[] proUnit, Double[] unitPrice, Double[] totalPrice, Double[] taxRate, Double[] taxAmount,
                                                Double[] unitPriceTaxIncluded, Double[] totalPriceIncludeTax, String[] remark, String[] taskIds, Integer[] payItem,
                                                String[] payCondition, Integer[] payPercent, Double[] payAmount, Integer[] payMethod) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            QuotationMain quotationMain = gentQuotationMain(quotationMainModel);//插入报价单主单
            insertQttDetail(quotationMain.getQuoteId(), proName,proNames, proType, proQty, proUnit, unitPrice, totalPrice, taxRate,
                            taxAmount, unitPriceTaxIncluded, totalPriceIncludeTax, remark, taskIds);//插入报价单明细
            insertQttPayItem(quotationMain.getQuoteId(), payItem, payCondition, payPercent, payAmount, payMethod);//插入付款明细
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("创建报价单成功！");
            logService.saveLog("创建报价单","报价单号：【"+quotationMain.getQuoteNo()+"】【"+user.getName()+"】报价单创建成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("创建报价单失败！");
        }
        return jsonResult;
    }

    /**
     * 插入付款明细
     * @param quoteId
     * @param payItem
     * @param payCondition
     * @param payPercent
     * @param payAmount
     * @param payMethod
     */
    private void insertQttPayItem(Integer quoteId, Integer[] payItem, String[] payCondition, Integer[] payPercent,
                                    Double[] payAmount, Integer[] payMethod) {

        for (int i = 0; i < payItem.length; i++){
            QuotationPayment quotationPayment = new QuotationPayment();
            quotationPayment.setPayItem(payItem[i]);
            if (payCondition.length != 0) {
                if (payCondition[i] == "") {
                    quotationPayment.setPayCondition(null);
                }
                if (payCondition[i] != null) {
                    quotationPayment.setPayCondition(payCondition[i]);
                }
            }
            if (payPercent.length != 0) {
                if (payPercent[i] != null) {
                    quotationPayment.setPayPercent(payPercent[i]);
                }
            }
            if (payAmount.length != 0) {
                if (payAmount[i] != null) {
                    quotationPayment.setPayAmount(BigDecimal.valueOf(payAmount[i]));
                }
            }
            if (payMethod.length != 0) {
                if (payMethod[i] != null) {
                    quotationPayment.setPayMethod(payMethod[i]);
                }
            }
            quotationPayment.setQttPayStatus(1);
            quotationPayment.setQuoteId(quoteId);
            quotationPaymentMapper.insertSelective(quotationPayment);
        }
    }

    /**
     * 插入报价明细
     * @param quoteId
     * @param proName
     * @param proNames
     * @param proType
     * @param proQty
     * @param proUnit
     * @param unitPrice
     * @param totalPrice
     * @param taxRate
     * @param taxAmount
     * @param unitPriceTaxIncluded
     * @param totalPriceIncludeTax
     * @param remark
     * @param taskIds
     */
    private void insertQttDetail(Integer quoteId, String[] proName, String[] proNames, String[] proType, Double[] proQty,
                                 String[] proUnit,Double[] unitPrice, Double[] totalPrice, Double[] taxRate, Double[] taxAmount,
                                 Double[] unitPriceTaxIncluded, Double[] totalPriceIncludeTax, String[] remark,String[] taskIds) {
        for (int i = 0; i < proName.length; i++) {
            QuotationSublist quotationSublist = new QuotationSublist();
            if (proName.length != 0) {
                if (proName[i] == "") {
                    quotationSublist.setProName(null);
                }
                if (proName[i] != null) {
                    quotationSublist.setProName(proName[i]);
                }
            }
            if (proNames.length != 0) {
                if (proNames[i] == "") {
                    quotationSublist.setProNames(null);
                }
                if (proNames[i] != null) {
                    quotationSublist.setProNames(proNames[i]);
                }
            }
            if (proType.length != 0) {
                if (proType[i] == "") {
                    quotationSublist.setProType(null);
                }
                if (proType[i] != null) {
                    quotationSublist.setProType(proType[i]);
                }
            }
            if (proQty.length != 0) {
                if (proQty[i] != null) {
                    quotationSublist.setProQty(BigDecimal.valueOf(proQty[i]));
                }
            }
            if (proUnit.length != 0) {
                if (proUnit[i] == "") {
                    quotationSublist.setProUnit(null);
                }
                if (proUnit[i] != null) {
                    quotationSublist.setProUnit(proUnit[i]);
                }
            }
            if (unitPrice.length != 0) {
                if (unitPrice[i] != null) {
                    quotationSublist.setUnitPrice(BigDecimal.valueOf(unitPrice[i]));
                }
            }
            if (totalPrice.length != 0) {
                if (totalPrice[i] != null) {
                    quotationSublist.setTotalPrice(BigDecimal.valueOf(totalPrice[i]));
                }
            }
            if (taxRate.length != 0) {
                if (taxRate[i] != null) {
                    quotationSublist.setTaxRate(BigDecimal.valueOf(taxRate[i]));
                }
            }
            if (taxAmount.length != 0) {
                if (taxAmount[i] != null) {
                    quotationSublist.setTaxAmount(BigDecimal.valueOf(taxAmount[i]));
                }
            }
            if (unitPriceTaxIncluded.length != 0) {
                if (unitPriceTaxIncluded[i] != null) {
                    quotationSublist.setUnitPriceTaxIncluded(BigDecimal.valueOf(unitPriceTaxIncluded[i]));
                }
            }
            if (totalPriceIncludeTax.length != 0) {
                if (totalPriceIncludeTax[i] != null) {
                    quotationSublist.setTotalPriceTaxIncluded(BigDecimal.valueOf(totalPriceIncludeTax[i]));
                }
            }
            if (remark.length != 0) {
                if (remark[i] == "") {
                    quotationSublist.setRemark(null);
                }
                if (remark[i] != null) {
                    quotationSublist.setRemark(remark[i]);
                }
            }
            quotationSublist.setQttAvaStatus(1);
            quotationSublist.setQuoteId(quoteId);
            quotationSublistMapper.insertSelective(quotationSublist);//插入报价明细

            List<String> taskIdsList = Arrays.asList(taskIds[i].split("/"));
            List<Task> taskList = new ArrayList<>();
            for(int j = 0; j < taskIdsList.size(); j ++)
            {
                Task task = new Task();
                if (taskIdsList.get(j) != null || taskIdsList.get(j) != ""){
                    task.setFkid(Integer.valueOf(taskIdsList.get(j)));
                    taskList.add(task);
                }
            }

            for(Task taskId : taskList)//插入关系
            {
                QttSubTaskRel qttSubTaskRel = new QttSubTaskRel();
                    qttSubTaskRel.setTaskFkId(taskId.getFkid());
                    qttSubTaskRel.setQttSubFkId(quotationSublist.getQttId());
                    qttSubTaskRelMapper.insertSelective(qttSubTaskRel);
            }
        }
    }

    /**
     * 保存报价单主单
     *
     * @param quotationMainModel
     * @return quotationMainModel
     */
    private QuotationMain gentQuotationMain(QuotationMainModel quotationMainModel) {
        QuotationMain quotationMain = new QuotationMain();
        User user = ShiroUtils.getUser();
        quotationMain.setQuoteDate(quotationMainModel.getQuoteDate());
        if(Integer.valueOf(quotationMainModel.getConsumerName()) != 0)//由于前端option传回的是客户id，需要重新查用户信息并赋值，如果传回值为0，没选择用户，则不赋值,否则查询后赋值
        {
            int consInfoId = Integer.valueOf(quotationMainModel.getConsumerName());
            QuotationMainModel quotationMainModel1 =
                    quotationMainDao.selectQttConsAttnInfo(consInfoId);
            quotationMain.setConsumerName(quotationMainModel1.getConsumerName());
            quotationMain.setCosType(quotationMainModel1.getCosType());
        }else {
            quotationMain.setConsumerName(null);
        }
        if (Integer.valueOf(quotationMainModel.getSupplierAttn()) != 0) //由于前端option传回的是卖方id，需要重新查用户信息并赋值，如果传回值为0，没选择卖方，则不赋值,否则查询后赋值
        {
            int id = Integer.valueOf(quotationMainModel.getSupplierAttn());
            SellerInfo sellerInfo = sellerInfoMapper.selectByPrimaryKey(id);
            quotationMain.setSupplierAttn(sellerInfo.getSellerName());
        }else {
            quotationMain.setSupplierAttn(null);
        }
        quotationMain.setSupplierTel(quotationMainModel.getSupplierTel());
        quotationMain.setSupplierEmail(quotationMainModel.getSupplierEmail());
        if(quotationMainModel.getDesign() != null){
            quotationMain.setDesign(quotationMainModel.getDesign());
        }else{
            quotationMain.setDesign(0);
        }
        if(quotationMainModel.getMaterial() != null){
            quotationMain.setMaterial(quotationMainModel.getMaterial());
        }else {
            quotationMain.setMaterial(0);
        }
        if(quotationMainModel.getManufature() != null){
            quotationMain.setManufature(quotationMainModel.getManufature());
        }else {
            quotationMain.setManufature(0);
        }
        if(quotationMainModel.getPackg() != null){
            quotationMain.setPackg(quotationMainModel.getPackg());
        }else {
            quotationMain.setPackg(0);
        }
        if(quotationMainModel.getTransport() != null){
            quotationMain.setTransport(quotationMainModel.getTransport());
        }else {
            quotationMain.setTransport(0);
        }
        if(quotationMainModel.getInstall() != null){
            quotationMain.setInstall(quotationMainModel.getInstall());
        }else {
            quotationMain.setInstall(0);
        }
        if(quotationMainModel.getDebug() != null){
            quotationMain.setDebug(quotationMainModel.getDebug());
        }else {
            quotationMain.setDebug(0);
        }
        quotationMain.setExcludeItem(quotationMainModel.getExcludeItem());
        quotationMain.setTotalAmountIncludedTax(quotationMainModel.getTotalAmountIncludedTax());
        quotationMain.setConsumerAttn(quotationMainModel.getConsumerAttn());
        quotationMain.setConsumerTel(quotationMainModel.getConsumerTel());
        quotationMain.setConsumerEmail(quotationMainModel.getConsumerEmail());
        quotationMain.setSupplierName(quotationMainModel.getSupplierName());
//        quotationMain.setSupplierAttn(quotationMainModel.getSupplierAttn());
//        quotationMain.setSupplierTel(quotationMainModel.getSupplierTel());
//        quotationMain.setSupplierEmail(quotationMainModel.getSupplierEmail());
        quotationMain.setQuoteBottomDesc(quotationMainModel.getQuoteBottomDesc()
                .replaceAll("\r\n|\r|\n|\n\r","<br>"));
        quotationMain.setCreateName(user.getName());
        quotationMain.setCreateAccount(user.getAccount());
        quotationMain.setQuoteId(quotationMainModel.getQuoteId());
        quotationMain.setQuoteGentDate(new Date());
        quotationMain.setQuoteAvaStatus(1);
        quotationMain.setQuoteStatus(1);
//        quotationMain.setQuoteNo(gentQuoteNo());
        quotationMain.setTransMethod(quotationMainModel.getTransMethod());

        quotationMainMapper.insertSelective(quotationMain);
        return quotationMain;
    }

    /**
     * 生成报价单号
     * @return 返回报价单号
     */
//    private String gentQuoteNo() {
//        // 取得当日零时时间
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTime(new Date());
//        calendar.set(Calendar.HOUR_OF_DAY, 0);
//        calendar.set(Calendar.MINUTE, 0);
//        calendar.set(Calendar.SECOND, 0);
//        Date date = calendar.getTime();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
//        String date1 = dateFormat.format(date);
//        Date date2 = null;
//        try {
//            date2 = dateFormat.parse(date1);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        List<QuotationMainModel> quotationMainModel = quotationMainDao.selectQuoteNoList(date2); // 查询当月是否有报价单
//        String quoteNo;//报价单生成规则202010100
//        if(quotationMainModel.size() == 0) //如果当月没有报价单，则生成第一条
//        {
//            quoteNo = dateFormat.format(new Date()).substring(0,6) + "001";
//        }else//如果已有报价单，则查找最后一个报价单号，按顺序生成下一个报价单号
//        {
//            quoteNo = dateFormat.format(new Date()).substring(0,6) ;
//            Integer quoteNo1 = Integer.parseInt(quotationMainModel.get(quotationMainModel.size()-1).getQuoteNo().substring(7, 9));
//            quoteNo = quoteNo + String.format("%03d",  quoteNo1 + 1);
//        }
//        return quoteNo;
//    }


    /**
     * 查询报价公司名*
     *
     * @return 公司名列表
     */
    public List<ConsumerInfoMainModel> findQttConsInfoList() {
//        ConsumerInfoMainModel consumerInfoMainModel = new ConsumerInfoMainModel();
//        consumerInfoMainModel.setConsInfoType(1);
        List<ConsumerInfoMainModel> consumerInfolist = quotationMainDao.selectQttConsInfoList();
        return consumerInfolist;
    }

    /**
     * 查询报价公司的联系人
     *
     * @return 联系人列表
     */
    public QuotationMainModel  findConsumer(Integer consInfoId) {
        QuotationMainModel quotationMainModel = quotationMainDao.selectQttConsAttn(consInfoId);
        return quotationMainModel;
    }

//    /**
//     * 查找联系人信息
//     *
//     * @param consInfoId 需方信息分表id
//     * @return 选择的联系人信息
//     */
//    public ConsumerInfoMainModel queryConsAttnInfo(Integer consInfoId) {
//        ConsumerInfoMainModel consumerInfoMainModel = quotationMainDao.selectQttConsAttnInfo(consInfoId);
//        return consumerInfoMainModel;
//    }

    /**
     * 根据报价单ID查找文件列表
     *
     * @param quoteId 报价单id
     * @return 文件列表
     */
    public List<FileManageModel> findQttFileList(int quoteId) {
        List<FileManageModel> fileManageModel = quotationMainDao.selectQttFileList(quoteId);
        return fileManageModel;
    }

    /**
     * 上传文件
     *
     * @param fileManageModel fileManageModel
     * @param file            文件
     * @return 行数
     */
    public JsonResult upload(FileManageModel fileManageModel, MultipartFile[] file) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            if (fileManageModel.getFileId() != null)//判断是否已存在文件id，如果存在id则进行更新附件信息
            {
//            if (null != file && file.length > 0)//判断上传的文件是否为空
//            {
//                for (MultipartFile f : file) {
                FileManage fileManage = new FileManage();
//                    String path = uploadPath + "quote/" + fileManageModel.getQuoteId() + "/" ;
//                    String fileName = FileUtils.upload(f, path);
//                    if (com.zhongwang.business.util.StringUtils.isNotNull(fileName)) {
//                        String url = "/files/quote/" + fileManageModel.getQuoteId() + "/" + fileName;
//                        if (quotationMainDao.countByUrl(url) > 0) {
//                            continue;
//                        }
                fileManage.setFileId(fileManageModel.getFileId());
//                        fileManage.setFileName(fileName);
                fileManage.setFileComment(fileManageModel.getFileComment());
                fileManage.setFileType(fileManageModel.getFileType());
//                        fileManage.setFileUploadDate(new Date());
//                        fileManage.setFileUrl(url);
//                        fileManage.setFilePath(path + fileName);
                fileManage.setUserId(user.getAccount());
                fileManage.setUserName(user.getName());
                fileManage.setMainId(fileManageModel.getQuoteId());
//                        fileManage.setFileStatus(1);
                updateDoc(fileManage);
                ;
//                    }
//                }
//            }
                fileManage = fileManageMapper.selectByPrimaryKey(fileManage.getFileId());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("文件信息修改成功!");
                logService.saveLog("修改文件信息","文件名称：【"+fileManage.getFileName()+"】【"+user.getName()+"】文件信息修改成功!");
            } else //否则进行插入文件信息
            {
                if (null != file && file.length > 0)//判断是否已存在文件id
                {
                    for (MultipartFile f : file) {
                        FileManage fileManage = new FileManage();
                        String path = uploadPath + "quote/" + fileManageModel.getQuoteId() + "/";
                        String fileName = FileUtils.upload(f, path);
                        if (com.zhongwang.business.util.StringUtils.isNotNull(fileName)) {
                            String url = "/files/quote/" + fileManageModel.getQuoteId() + "/" + fileName;
                            if (quotationMainDao.countByUrl(url) > 0) {
                                continue;
                            }
                            fileManage.setFileName(fileName);
                            fileManage.setFileComment(fileManageModel.getFileComment());
                            fileManage.setFileType(fileManageModel.getFileType());
                            fileManage.setFileUploadDate(new Date());
                            fileManage.setFileUrl(url);
                            fileManage.setFilePath(path + fileName);
                            fileManage.setUserId(user.getAccount());
                            fileManage.setUserName(user.getName());
                            fileManage.setMainId(fileManageModel.getQuoteId());
                            fileManage.setFileStatus(1);
                            fileManageMapper.insertSelective(fileManage);
                            jsonResult.setType(JsonResult.ResultType.SUCCESS);
                            jsonResult.setMsg("上传文件成功!");
                            logService.saveLog("上传文件","文件名称：【"+fileManage.getFileName()+"】【"+user.getName()+"】上传文件成功!");
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("上传/修改文件失败!");
        }
        return jsonResult;
    }

    /**
     * 报价单列表
     *
     * @param query 查询条件
     * @return 列表数据
     */
    public List<QuotationMainModel> findQuoteList(QuotationMainModel query) {
        User user = ShiroUtils.getUser();
        query.setAccount(user.getAccount());
        if(query.getQuoteAvaStatus()!=null && query.getQuoteAvaStatus() == 2){
            query.setQuoteStatus(100);
        }
        List<QuotationMainModel> quotationMainModelList = quotationMainDao.selectQuoteList(query);
        int m = quotationMainModelList.size();
        for(int i = 0; i < m; i++){
            List<QuotationSublistModel> quotationSublistModelList = quotationQueryDao.selectQttProNameList(quotationMainModelList.get(i).getQuoteId());
            String name = "";
            String code = "";
            for (int k= 0; k < quotationSublistModelList.size(); k++){
                name = name + quotationSublistModelList.get(k).getProName() + ",";
                code = code + quotationSublistModelList.get(k).getProCode() + ",";
            }
            quotationMainModelList.get(i).setProName(name);
            quotationMainModelList.get(i).setProCode(code);
        }
        return quotationMainModelList;
    }

    /**
     * 报价单明细列表 (通过报价单id查找)
     * @param quoteId 查询条件
     * @return 列表数据
     */
    public List<QuotationSublistModel> findQttList(Integer quoteId) {
        List<QuotationSublistModel> quotationSublistModel = quotationMainDao.selectQttList(quoteId);
        return quotationSublistModel;
    }

    /**
     * 根据文件id查询文件信息
     * @param fileId
     * @return 查找信息
     */
    public FileManage getFileById(Integer fileId) {
        return fileManageMapper.selectByPrimaryKey(fileId);
    }

    /**
     * 修改和删除报价文件
     * @param doc 报价文件信息
     * @return 返回行数
     */
    public int updateDoc(FileManage doc) {
        return fileManageMapper.updateByPrimaryKeySelective(doc);
    }

    /**
     * 提交报价单
     * 更新报价单状态
     * 生成报价审核流程
     * @param quotationMain 报价信息
     * @return 行数
     */
    public JsonResult submitQuote(QuotationMain quotationMain) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
             SheetDetail sheetDetail1 = quotationMainDao.selectSheetDetail(quotationMain.getQuoteId());
            if(sheetDetail1 == null || sheetDetail1.getId() == null){
                SheetDetail sheetDetail =  new SheetDetail();
                sheetDetail.setBllId(quotationMain.getQuoteId());
                sheetDetail.setSubmitTime(new Date());
                sheetDetail.setSubmitUser(user.getId());
                sheetDetail.setAppType(2);
                sheetDetailMapper.insertSelective(sheetDetail);
                VerifyProcessModel verifyProcessModel = quotationMainDao.selectStartNode(user.getId());
                VerifyProcess verifyProcess = new VerifyProcess();
                verifyProcess.setSheetId(sheetDetail.getId());
                verifyProcess.setCode("BJ001");
                verifyProcess.setAppStatus(1);
                verifyProcess.setNowNode(verifyProcessModel.getNowNode());
                verifyProcessMapper.insert(verifyProcess);
                quotationMain.setQuoteStatus(2);
                quotationMainMapper.updateByPrimaryKeySelective(quotationMain);
                quotationMain = quotationMainDao.selectQttInfo(quotationMain.getQuoteId());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("报价单提交成功！");
                logService.saveLog("报价单提交","报价单号：【"+quotationMain.getQuoteNo()+"】【"+user.getName()+"】提交成功!");
            }else if(sheetDetail1.getId() != null){
                sheetDetail1.setSubmitTime(new Date());
                sheetDetail1.setSubmitUser(user.getId());
                sheetDetailMapper.updateByPrimaryKeySelective(sheetDetail1);
                VerifyProcessModel verifyProcessModel = quotationMainDao.selectStartNode(user.getId());
                VerifyProcess verifyProcess = new VerifyProcess();
                verifyProcess.setSheetId(sheetDetail1.getId());
                verifyProcess.setCode("BJ001");
                verifyProcess.setAppStatus(1);
                verifyProcess.setNowNode(verifyProcessModel.getNowNode());
                verifyProcessMapper.insert(verifyProcess);
                quotationMain.setQuoteStatus(2);
                quotationMainMapper.updateByPrimaryKeySelective(quotationMain);
                quotationMain = quotationMainDao.selectQttInfo(quotationMain.getQuoteId());
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setMsg("报价单提交成功！");
                logService.saveLog("报价单提交","报价单号：【"+quotationMain.getQuoteNo()+"】【"+user.getName()+"】提交成功!");
            }else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setMsg("报价单提交失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价单提交失败！");
        }
        return jsonResult;
    }

    /**
     * 删除报价
     *
     * @param quotationMain
     * @return 行数
     */
    public JsonResult delQuote(QuotationMain quotationMain) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {

            //删除报价子单与关系
            List<QttSubTaskRel> qttSubTaskRelList = quotationQueryDao.selectQttSubTaskRelList(quotationMain.getQuoteId());
            if(qttSubTaskRelList.size() != 0){
                for (QttSubTaskRel qttSubTaskRel: qttSubTaskRelList) {
                    qttSubTaskRelMapper.deleteByPrimaryKey(qttSubTaskRel.getId());
                }
            }

            //删除报价子单
            List<QuotationSublistModel> quotationSublistList = quotationMainDao.selectQttList(quotationMain.getQuoteId());
            if (quotationSublistList.size() != 0){
                for(QuotationSublist quotationSublist: quotationSublistList){
                    quotationSublistMapper.deleteByPrimaryKey(quotationSublist.getQttId());
                }
            }

            //删除报价款项
            List<QuotationPaymentModel> quotationPaymentModelList = quotationMainDao.selectQttItemList(quotationMain.getQuoteId());
            if(quotationPaymentModelList.size() != 0){
                for(QuotationPayment quotationPayment: quotationPaymentModelList){
                    quotationPaymentMapper.deleteByPrimaryKey(quotationPayment.getQttPayId());
                }
            }

            //更新报价主单状态为0
            quotationMain.setQuoteAvaStatus(0);
            quotationMainMapper.updateByPrimaryKey(quotationMain);
            quotationMain = quotationMainDao.selectQttInfo(quotationMain.getQuoteId());
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("报价单删除成功！");
            logService.saveLog("删除报价单","报价单号：【"+quotationMain.getQuoteNo()+"】【"+user.getName()+"】删除成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价单删除失败！");
        }
        return jsonResult;
    }

    /**
     * 增加报价明细列表查询
     *
     * @param query
     * @return 列表
     */
//    public List<QuotationMainModel> findQuoteAddList(QuotationMainModel query) {
//        List<QuotationMainModel> findQuoteAddList = quotationMainDao.selectQuoteAddList(query);
//        if (query.getTasksIdAdd().equals("")) {
//            query.setTasksIdAdd(null);
//        }
//        if (query.getTasksIdAdd() != null) {
//            List<String> tasksIdAddList = Arrays.asList(query.getTasksIdAdd().split(","));
//            for (String tasksIdAdd : tasksIdAddList) {
//                Iterator<QuotationMainModel> p = findQuoteAddList.iterator();
//                while (p.hasNext()) {
//                    if (p.next().getQuoteTaskId().equals(Integer.valueOf(tasksIdAdd))) {
//                        p.remove();
//                    }
//                }
//            }
//        }
//        return findQuoteAddList;
//    }

    /**
     * 根据报价明细id查询报价明细信息
     *
     * @param qttId
     * @return 报价信息
     */
    public QuotationSublist getQttById(Integer qttId) {
        return quotationSublistMapper.selectByPrimaryKey(qttId);
    }

    /**
     * 编辑保存报价单主单及子单
     * @param quotationMainModel
     * @param proName
     * @param proType
     * @param proQty
     * @param proUnit
     * @param unitPrice
     * @param totalPrice
     * @param taxRate
     * @param taxAmount
     * @param unitPriceTaxIncluded
     * @param totalPriceIncludeTax
     * @param remark
     * @param proNames
     * @param taskIds
     * 更新主单信息，再将子单信息清空，且将报价明细关联的报价任务状态置为未开始，开始时间置空；
     *                             再将关系表中的报价主单id清空；
     *                             重新插入子单；将报价明细关联的报价任务状态置为执行中，开始时间置为new Date；
     *                             再将关系表中的报价主单id置为当前主单id
     * @return
     */
    public JsonResult quotationUpdateSave(QuotationMainModel quotationMainModel, String[] proName, String[] proNames, String[] proType, Double[] proQty,
                                          String[] proUnit, Double[] unitPrice, Double[] totalPrice, Double[] taxRate, Double[] taxAmount,
                                          Double[] unitPriceTaxIncluded, Double[] totalPriceIncludeTax, String[] remark, String[] taskIds, Integer[] payItem,
                                          String[] payCondition, Integer[] payPercent, Double[] payAmount, Integer[] payMethod) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            List<QuotationSublistModel> quotationSublistModelList = quotationMainDao.selectQttList(quotationMainModel.getQuoteId());//根据报价单id查找报价单子单列表
            for (QuotationSublistModel quotationSublistModel : quotationSublistModelList)//循环列表将报价子单删除
            {
                quotationSublistMapper.deleteByPrimaryKey(quotationSublistModel.getQttId());
                List<QttSubTaskRel> qttSubTaskRelList = quotationMainDao.selectQttTaskRelListByQttId(quotationSublistModel.getQttId());//根据报价子单删除报价子单和任务关系
                for(QttSubTaskRel qttSubTaskRel: qttSubTaskRelList)
                {
                    qttSubTaskRelMapper.deleteByPrimaryKey(qttSubTaskRel.getId());
                }
            }
            List<QuotationPaymentModel> quotationPaymentModelList = quotationMainDao.selectQttItemList(quotationMainModel.getQuoteId());//根据报价单id查找款项列表
            for(QuotationPaymentModel quotationPaymentModel : quotationPaymentModelList)//循环列表将款项删除
            {
                quotationPaymentMapper.deleteByPrimaryKey(quotationPaymentModel.getQttPayId());
            }
    //        List<Task> taskList = quotationMainDao.selectQttTaskListByQuoteId(quotationMainModel.getQuoteId());//根据报价单主单id查找报价任务
    //        for (Task task : taskList)//将关系表的报价单id去掉，将报价任务的状态和开始时间置为初始状态
    //        {
    //            task = quotationMainDao.selectQttTaskList(task.getId());
    //            task.setTstatus(1);
    //            task.setBeginDate(null);
    //            task.setKeyPersonId(null);
    //            task.setKeyPerson(null);
    //            quotationMainDao.updateTask(task);
    //        }
    //
    //        for (int i = 0; i < proCode.length; i++) //更新任务表的任务状态为执行中、开始时间
    //        {
    //            Task task = quotationMainDao.selectByProCode(proCode[i]);
    //            task.setBeginDate(new Date());
    //            task.setTstatus(2);
    //            task.setKeyPerson(user.getName());
    //            task.setKeyPersonId(user.getId());
    //            taskMapper.updateByPrimaryKeySelective(task);
    //        }
            insertQttDetail(quotationMainModel.getQuoteId(), proName,proNames, proType, proQty, proUnit, unitPrice, totalPrice, taxRate,
                    taxAmount, unitPriceTaxIncluded, totalPriceIncludeTax, remark, taskIds);//插入报价单明细
            insertQttPayItem(quotationMainModel.getQuoteId(), payItem, payCondition, payPercent, payAmount, payMethod);//插入报价付款项
            QuotationMainModel quotationMainModel1 =
                quotationMainDao.selectQuotationTotalAmountById(quotationMainModel.getQuoteId()); //重新计算总价
            quotationMainModel.setTotalAmountIncludedTax(quotationMainModel1.getTotalAmountIncludedTax());
            if(quotationMainModel.getDesign() != null){
                quotationMainModel.setDesign(quotationMainModel.getDesign());
            }else {
                quotationMainModel.setDesign(0);
            }

            if(quotationMainModel.getMaterial() != null){
                quotationMainModel.setMaterial(quotationMainModel.getMaterial());
            }else {
                quotationMainModel.setMaterial(0);
            }

            if(quotationMainModel.getManufature() != null){
                quotationMainModel.setManufature(quotationMainModel.getManufature());
            }else {
                quotationMainModel.setManufature(0);
            }

            if(quotationMainModel.getPackg() != null){
                quotationMainModel.setPackg(quotationMainModel.getPackg());
            }else {
                quotationMainModel.setPackg(0);
            }

            if(quotationMainModel.getTransport() != null){
                quotationMainModel.setTransport(quotationMainModel.getTransport());
            }else {
                quotationMainModel.setTransport(0);
            }

            if(quotationMainModel.getInstall() != null){
                quotationMainModel.setInstall(quotationMainModel.getInstall());
            }else {
                quotationMainModel.setInstall(0);
            }

            if(quotationMainModel.getDebug() != null){
                quotationMainModel.setDebug(quotationMainModel.getDebug());
            }else {
                quotationMainModel.setDebug(0);
            }
            if(Integer.valueOf(quotationMainModel.getConsumerName()) != 0) //由于前端option传回的是客户id，需要重新查用户信息并赋值，如果传回值为0，未变更，则不重新赋值,否则重新赋值
            {
                int consInfoId = Integer.valueOf(quotationMainModel.getConsumerName());
                QuotationMainModel quotationMainModel2 = quotationMainDao.selectQttConsAttn(consInfoId);
                quotationMainModel.setConsumerName(quotationMainModel2.getConsumerName());
                quotationMainModel.setCosType(quotationMainModel2.getCosType());
            }else {
                quotationMainModel.setConsumerName(null);//不更新客户名
            }
            if(Integer.valueOf(quotationMainModel.getSupplierAttn()) != 0) //由于前端option传回的是客户id，需要重新查用户信息并赋值，如果传回值为0，未变更，则不重新赋值,否则重新赋值
            {
                int id = Integer.valueOf(quotationMainModel.getSupplierAttn());
                SellerInfo sellerInfo1 = sellerInfoMapper.selectByPrimaryKey(id);
                quotationMainModel.setSupplierAttn(sellerInfo1.getSellerName());
            }else {
                quotationMainModel.setSupplierAttn(null);//不更新客户名
            }
            quotationMainModel.setQuoteBottomDesc(quotationMainModel.getQuoteBottomDesc()
                    .replaceAll("\r\n|\r|\n|\n\r","<br>"));
            quotationMainDao.updateQuote(quotationMainModel);
            quotationMainModel = quotationMainDao.selectQttInfo(quotationMainModel.getQuoteId());
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("报价单修改成功！");
            logService.saveLog("报价单修改","报价单号：【"+quotationMainModel.getQuoteNo()+"】【"+user.getName()+"】修改成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价单修改失败！");
        }
        return jsonResult;
    }

    /**
     * 根据输入的字符串查找项目
//     * @param q 输入的字符串
     * @return 项目编号列表
     */
//    public List<TaskModelQ> findProjectByCode(String q) {
//      return  quotationMainDao.selectProjectByCode(q);
//    }

    /**
     * 查询选中的任务id，任务信息
//     * @param quoteTaskId 任务id
     * @return 任务信息
     */
//    public QuotationMainModel findQuoteTaskInfo(Integer quoteTaskId) {
//        return quotationMainDao.selectTaskById(quoteTaskId);
//    }

    /**
     * 选择待报价任务的列表
     * @return 列表数据
     */
    public List<QuotationMainModel> findQttTaskList(QuotationMainModel query) {
        return quotationMainDao.selectQttTaskPreList(query);
    }

    /**
     * 修改报价创建人
     * @param quotationMain
     * @return
     */
    public JsonResult updateCreateAccount(QuotationMainModel quotationMain) {
        JsonResult jsonResult = new JsonResult();
        User user = ShiroUtils.getUser();
        try {
            SysUser sysUser = quotationMainDao.selectByAccount(quotationMain.getCreateAccount());
            QuotationMain quotationMain1 = quotationMainMapper.selectByPrimaryKey(quotationMain.getQuoteId());
            quotationMain.setQuoteNo(quotationMain1.getQuoteNo());
            quotationMain.setCreateName(sysUser.getName());
            quotationMainMapper.updateByPrimaryKeySelective(quotationMain);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("报价单创建人修改成功！");
            logService.saveLog("报价单创建人修改","报价单号：【"+quotationMain.getQuoteNo()+"】【"+user.getName()+"】修改成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("报价单创建人修改失败！");
        }
        return jsonResult;
    }
}
